﻿namespace Blaze.Editor.AssetValidators
{
    using Build;
    using UnityEditor;
    using UnityEngine;

    /// <summary>
    /// 引用丢失检测。
    /// </summary>
    public class MissingReference : AssetValidator
    {
        /// <summary>
        /// 检查指定资源是否满足校验规则。
        /// </summary>
        /// <param name="asset">资源</param>
        public override void Check(Object asset)
        {
            var prefab = asset as GameObject;
            if (prefab == null)
                return;

            var components = prefab.transform.GetComponentsInChildren<Component>(true);
            foreach (var component in components)
            {
                if (component == null)
                {
                    Logger.Error("脚本丢失");
                    continue;
                }

                var serializedObject = new SerializedObject(component);
                var sp = serializedObject.GetIterator();

                while (sp.NextVisible(true))
                {
                    if (sp.propertyType != SerializedPropertyType.ObjectReference)
                        continue;
                    if (sp.objectReferenceValue == null && sp.objectReferenceInstanceIDValue != 0)
                        Logger.ErrorFormat("引用丢失：{0} {1}", component, sp.propertyPath);
                }
            }
        }

        /// <summary>
        /// 获取一个值，表示某个资源是否需要校验，用于预校验，省去加载资源的开销。
        /// </summary>
        /// <param name="assetPath">资源路径</param>
        public override bool Precheck(string assetPath)
        {
            return BuildSettings.IsBuiltinAssetReferencableAsset(assetPath);
        }
    }
}